<template>
	<view>
		<view class="flex justify-around  padding">
			<!-- <view class="flex-sub text-white text-center">答题记录</view>
			<view class="flex-sub text-white text-center">规则说明</view> -->
		</view>
		<!-- 头像区域 -->

		<view class="flex flex-direction justify-center align-center" style="height: 365px;width: 100%;">
			<view class="cu-avatar xl round " :style="'background-image: url(' + userinfo.avatarUrl + ');'">
				<view class="cu-tag badge light	 bg-blue">发起者</view>
			</view>
			<!-- 名字 -->
			<view class="text-xxl text-white margin-top text-bold">{{ userinfo.nickName }}</view>
			<!-- 积分 -->
			<!-- <view class="text-xxl text-white margin-top text-bold">积分:120</view> -->

		</view>

		<view class="flex justify-center align-center" style="width: 100%;">
			<view class="flex justify-center align-center justify-around" style="height: 130px;width: 340px;gap: 10px;">
				<!-- <view class="flex flex-sub flex-direction justify-center align-center radius  "
					style="background: #FF9797;height: 100%;">
					<view class="iconsize icon1"> </view>
					<view class="text-xl text-white text-bold">邀请好友</view>
				</view> -->
				<view @tap="randomPk" class="flex flex-sub flex-direction justify-center align-center radius  "
					style="background: #97C9FF;height: 100%;">
					<view class="iconsize icon2"> </view>
					<view class="text-xl text-white text-bold">随机匹配</view>
				</view>
			</view>

		</view>
		<view v-if="loadModal" @tap="cancel()" class="text-xl bg-white qxpp">取消匹配</view>
		<view class="cu-load load-modal" v-if="loadModal">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<view class="gray-text">随机匹配中...</view>
		</view>
	</view>
</template>

<script>
import loginjs from '../../core/login'
export default {
	data() {
		return {
			data: {
				onMessageListPage: true, //是否在消息列表页
				socketOpen: false, //是否开启了websocket
				current_passive_uid: -1, //当前聊天对象
				heartbeat_delay: 50000, //心跳时间
				message_page: 1, //当前消息列表页面，每页20个列表
				message_list: [], //用于渲染的消息列表数据
				unreadcount: 0, //总未读消息数
				reconnect_delay: 5000, //重连延迟
				eventChannel: null //与chat的通信接口
			},
			loadModal: false,//匹配中
			userinfo: {},//用户信息

		}
	},
	onShow() {
		this.islogin()
	},
	onLoad(options) {
		uni.setStorageSync('type', 0)//当前为随机 完成答题跳转再来一次用的标记

		this.openWebSocket()//开启websocket
		this.init()//初始化
		this.islogin()//判断是否登录
	},
	methods: {
		islogin() {
			console.log('nihao ');
			console.log('%c [ loginjs.checkIfLogin ]-72', 'font-size:13px; background:pink; color:#bf2c9f;', loginjs.checkIfLogin())

			if (loginjs.checkIfLogin() == false) {
				// 弹窗提示请登录后操作
				uni.showToast({
					title: '请先登录',
					icon: 'none',
				})

				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/auth/login/index'
					})
				}, 1000);
			}
		},
		//取消匹配的函数
		init() {
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			console.log('%c [ parsedData ]-71', 'font-size:13px; background:pink; color:#bf2c9f;',)
			this.userinfo = parsedData.userinfo
		},
		cancel() {
			this.loadModal = false
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			this.sendMsg({
				"type": "cancel_matching",
				"token": tokenValue,
				"match_type": 0
			})
			uni.showToast({
				title: '取消匹配',
				icon: 'none',
				mask: true
			})
		},
		randomPk() {
			this.loadModal = true
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			this.sendMsg({
				"type": "matching",
				"token": tokenValue,
				"match_type": 0
			})
		},

		sendMsg(data) {
			wx.sendSocketMessage({
				data: JSON.stringify(data)
			})
		},
		openWebSocket() {
			let that = this
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;

			wx.connectSocket({
				url: that.$myHttp.urlMap.chat,
				header: {
					'content-type': 'application/json',
					'from': 'wechatmini'
				}
			})
			wx.onSocketMessage((msg) => {
				let data = JSON.parse(msg.data)
				console.log('webdata: ', data)
				switch (data.data.type) {
					case 'opponent_winner':
						console.log('opponent_winner,我赢了')
						uni.$emit('yingle')
						break;
					case 'opponent_loser':
						console.log('opponent_loser,我输了')
						uni.$emit('shule')
						break;
					case 'exit_matching_success':
						console.log('exit_matching_success,我退出了')
						uni.$emit('shule')
						break;
					case 'exit_matching_failed':
						console.log('exit_matching_failed,我退出失败了')
						uni.$emit('shule')
						break;
					case 'cannot_win':
						console.log('cannot_win,异常错误')
						uni.$emit('shule')
						break;

					case 'matching_wait':
						//等待
						that.loadModal = true
						console.log('等待matching_wait')
						break;
					case 'matching_success':
						//成功
						console.log('成功状态matching_success')
						setTimeout(() => {
							that.loadModal = false
							uni.showToast({
								title: '匹配成功',
								icon: 'success',
								duration: 3000
							})

						}, 1000);

						setTimeout(() => {
							that.$openrul('/pages/randomPk/randomPk?my=' + JSON.stringify(that.userinfo) + '&orther=' + msg.data + '&type=0')
						}, 3000);

						//跳转
						break;
					case 'matching_error':
						//错误状态
						console.log('错误状态matching_error')
						setTimeout(() => {
							that.loadModal = false
							uni.showToast({
								title: '匹配失败',
								icon: 'error',
								duration: 2000
							})
						}, 1000);
						// 提示，出现错误
						break;
				}
			})
			wx.onSocketOpen((msg) => {
				that.data.socketOpen = true
				that.sendMsg({
					type: 'login',
					token: tokenValue
				})
				console.log('WebSocket登录')
				//心跳
				that.data.pong = setInterval(() => {
					that.sendMsg({
						type: 'pong'
					})
				}, that.data.heartbeat_delay);
			})
			wx.onSocketClose((msg) => {
				clearInterval(that.data.pong)
				//reconnect
				that.data.socketOpen = false
				let i = setInterval(() => {
					wx.connectSocket({
						url: that.$myHttp.urlMap.chat,
						header: {
							'content-type': 'application/json',
							'from': 'wechatmini'
						}
					})
					console.log('reconnect')
					if (that.data.socketOpen) clearInterval(i)
				}, that.data.reconnect_delay)
			})
		},
	}
}
</script>

<style>
.qxpp {
	position: fixed;
	top: 0;
	right: 0;
	bottom: -300rpx;
	left: 0;
	margin: auto;
	width: 260rpx;
	height: 50rpx;
	background-color: #ffffff;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	flex-direction: column;
	justify-content: center;
	font-size: 28rpx;
	z-index: 99999;
	line-height: 2.4em;
}

page {
	background-image: url('');
	background-size: cover;
}

.iconsize {
	width: 53px;
	height: 53px;
}

.icon1 {
	background-image: url('');
	background-size: cover;
}

.icon2 {
	background-image: url('');
	background-size: cover;
}
</style>
